﻿using CloudDiamonds.Models.DBModels;
using CloudDiamonds.Models.Manager;
using CloudDiamonds.Models.Manager.Diamonds;
using CloudDiamonds.Models.Manager.Parcel;
using CloudDiamonds.Models.Manager.Product;
using CloudDiamonds.Models.Manager.Supplier;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Yunzuan.Foundation.DataAccess;
using Yunzuan.Foundation.Entities;
using Yunzuan.Foundation.Log;

namespace WholesalerService.Common
{
    public class DiamondsPriceHandler
    {
        private static Dictionary<string, SupplierInfo> suppliers = new Dictionary<string, SupplierInfo>();

        //供应商白钻和彩钻折扣 9-27
        public static SupplierInfo GetSuppliers(string supplierCode)
        {
            //supplierCode一律转大写
            supplierCode = supplierCode.ToUpper();

            try
            {
                if (System.Web.HttpContext.Current != null)
                {

                    if (System.Web.HttpContext.Current.Cache.Get("Cache:Suppliers" + supplierCode) == null)
                    {
                        PageParam param = new PageParam();

                        param.PageIndex = 1;
                        param.PageSize = 9999;//内置9999家

                        //获取供应商信息 9-27
                        PageList<SupplierInfo> result = YZ.Database.QueryForList<SupplierInfo>("Supplier.GetList", param, param.PageSize, param.PageIndex);

                        foreach (var item in result.Data)
                        {
                            if (!item.Rebate.HasValue) { item.Rebate = 0; }
                            if (!item.FancyRebate.HasValue) { item.FancyRebate = 0; }
                            if (!item.GemRebate.HasValue) { item.GemRebate = 1; }
                            if (!item.RingRebate.HasValue) { item.RingRebate = 1; }
                            if (!item.ParcelRebate.HasValue) { item.ParcelRebate = 1; }
                            if (!item.EmeraldRebate.HasValue) { item.EmeraldRebate = 1; }
                            if (!item.InlaySettingsRebate.HasValue) { item.InlaySettingsRebate = 1; }
                            suppliers[item.SupplierCode.ToUpper()] = item;//一律转成大写SupplierCode
                        }
                        System.Web.HttpContext.Current.Cache["Cache:Suppliers" + supplierCode] = suppliers;
                        return suppliers[supplierCode];
                    }
                    else
                    {
                        var supplierInfo = (Dictionary<string, SupplierInfo>)System.Web.HttpContext.Current.Cache["Cache:Suppliers" + supplierCode];
                        if (supplierInfo.ContainsKey(supplierCode))
                            return supplierInfo[supplierCode];
                    }
                }
                else
                {
                    PageParam param = new PageParam();

                    param.PageIndex = 1;
                    param.PageSize = 9999;//内置9999家
                    PageList<SupplierInfo> result = YZ.Database.QueryForList<SupplierInfo>("Supplier.GetList", param, param.PageSize, param.PageIndex);

                    foreach (var item in result.Data)
                    {
                        if (!item.Rebate.HasValue) { item.Rebate = 0; }
                        if (!item.FancyRebate.HasValue) { item.FancyRebate = 0; }
                        if (!item.GemRebate.HasValue) { item.GemRebate = 1; }
                        if (!item.RingRebate.HasValue) { item.RingRebate = 1; }
                        if (!item.ParcelRebate.HasValue) { item.ParcelRebate = 1; }
                        if (!item.EmeraldRebate.HasValue) { item.EmeraldRebate = 1; }
                        if (!item.InlaySettingsRebate.HasValue) { item.InlaySettingsRebate = 1; }
                        suppliers[item.SupplierCode.ToUpper()] = item;//一律转成大写SupplierCode
                    }
                    return suppliers[supplierCode]; 
                }
                    
            }
            catch (Exception ex)
            {
                throw;
                //供应商报错 9-27
            }

            //供应商不存在
            return new SupplierInfo { Rebate = 0, FancyRebate = 0, GemRebate = 1, RingRebate = 1, ParcelRebate = 1,EmeraldRebate=1, ShipTime = "" };
        }

        public static string[] GetSuppliers()
        {
            if (HttpRuntime.Cache.Get("Priorities") == null)
            {
                PageParamOfInventory ppoi = new PageParamOfInventory();
                return ppoi.CachePriorities();
            }
            else
                return HttpRuntime.Cache.Get("Priorities") as string[];
        }

        /// <summary>
        /// 计算价格 - 裸钻 Loose Diamond
        /// </summary>
        /// <param name="item"></param>
        /// <param name="customer">CustomerInfo customer=null 微信的用户不支持调价，所以屏蔽</param>
        /// <param name="setting"></param>
        public static void ComputePrice(InventoryInfoResult item, SysSettingInfo setting, CustomerInfo customer = null)
        {

            if (item == null)
            {
                return;
            }
            try
            {
                if (item.ShipTime.IndexOf("1970") > -1) //如果是初始值 ，则使用供应商的设置
                {
                    item.ShipTime = GetSuppliers(item.Supplier).ShipTime;
                } 
                decimal sourceDisc = 0;//临时退点
                decimal tempDouble = 1; //临时存储白或彩的倍率
                //彩钻
                if (item.IsFancy == 1)
                {

                    //分析4c折扣-彩钻
                    IList<Group_4C> lv2FancyDiss = GetGroupCCCC(2, setting.GroupFancy4C); //2为彩 ,1 为白
                    decimal globalDis = 0;// GoodsType.GetGlobalFancyDiscountReturn(setting); 
                    //分组彩
                    if (lv2FancyDiss != null)
                    {
                        var shape = 0;  //存储异形或圆形
                        foreach (var item2 in lv2FancyDiss)
                        {
                            int sha = item2.Shape == "round" ? 1 : 2;
                            //item.Weight   0.31-0.36
                            decimal minWeight = item2.MinWeight;
                            decimal maxWeight = item2.MaxWeight;
                            shape = item.Shape > 1 ? 2 : 1;  //设置为圆形或者异形
                            shape = item.Shape == 1 ? 1 : 2;  //设置为圆形或者异形
                            if (shape == sha && item.Weight >= minWeight && item.Weight <= maxWeight)
                            {
                                ///全局折扣+=加上分组折扣(彩)
                                globalDis = globalDis + item2.Dis;
                                tempDouble = item2.Double == 0 ? 1 : item2.Double;   //有分组倍率，则全局*分组  合并为全局倍率
                                break;
                            }
                        }
                    }
                    decimal fancyRebate = GetSuppliers(item.Supplier).FancyRebate.Value;
                    //彩钻价格计算
                    item.DiscountReturn = globalDis + fancyRebate;
                    item.DolarPerGrain = (decimal)item.SourceDolarPerGrain * (decimal)((100 + fancyRebate) / 100) * (decimal)((100 + globalDis) / 100) * tempDouble; //只在粒上乘以倍率
                    item.DolarPerCarat = item.DolarPerGrain / (decimal)item.Weight;
                    item.RMBPerGrain = item.DolarPerGrain * GetRate(setting); //只在粒上乘以倍率
                    item.RMBPerCarat = item.DolarPerGrain / (decimal)item.Weight * GetRate(setting);
                    item.SourceDolarPerCarat = Math.Round(item.SourceDolarPerGrain.Value / Convert.ToDecimal(item.Weight), 1, MidpointRounding.AwayFromZero);
                    if (customer != null)
                    {
                        item.CustomerDolarPerGrain = (decimal)(item.SourceDolarPerGrain * (decimal)((100 + globalDis) / 100) * (decimal)((100 + fancyRebate) / 100) * (decimal)((100 + customer.FancyRebate.Value) / 100)) * tempDouble; //只在粒上乘以倍率
                        item.CustomerDolarPerCarat = item.CustomerDolarPerGrain.Value / Convert.ToDecimal(item.Weight);
                        item.CustomerRMBPerGrain = item.CustomerDolarPerGrain * GetRate(setting); //只在粒上乘以倍率;
                        item.CustomerRMBPerCarat = item.CustomerRMBPerGrain.Value / Convert.ToDecimal(item.Weight);
                    } 
                }
                //白钻价格
                else
                {

                    //分析4c折扣-白钻
                    IList<Group_4C> lv2Diss = GetGroupCCCC(1, setting.Group4C);  //2为彩 ,1 为白//白钻分组数据(匹配成想要的格式)
                    //分组白
                    if (lv2Diss != null)
                    {
                        var shape = 0;  //存储异形或圆形
                        foreach (var item2 in lv2Diss)
                        {
                            int sha = item2.Shape == "round" ? 1 : 2; //规则

                            //item.Weight   0.31-0.36

                            decimal minWeight = item2.MinWeight;
                            decimal maxWeight = item2.MaxWeight;
                            shape = item.Shape > 1 ? 2 : 1;  //设置为圆形或者异形
                            if (shape == sha && item.Weight >= minWeight && item.Weight <= maxWeight)
                            {
                                //全局折扣+=加上分组折扣(白)
                                sourceDisc += item2.Dis;
                                tempDouble = item2.Double == 0 ? 1 : item2.Double;  //有分组倍率，则全局*分组  合并为全局倍率
                                break;
                            }
                        }
                    }

                    sourceDisc += item.SourceDiscountReturn.Value;
                    //原退点 +当前供应商的退点
                    sourceDisc += GetSuppliers(item.Supplier).Rebate.Value;
                    //原退点 +当前供应商的退点 +全局退点
                    //sourceDisc += GoodsType.GetGlobalDiscountReturn(setting);
                    //discount=CalcWhiteReturnPoint(
                    item.DiscountReturn = sourceDisc;
                    //美金克拉价格
                    item.DolarPerCarat = (decimal)(item.Rapnet * ((100 + sourceDisc) / 100)) * tempDouble;
                    //美金单粒价格
                    item.DolarPerGrain = item.DolarPerCarat * (decimal)item.Weight.Value; //只在粒上乘以倍率
                    item.RMBPerCarat = item.DolarPerCarat * GetRate(setting);//报错？
                    item.RMBPerGrain = item.RMBPerCarat * (decimal)item.Weight.Value; //只在粒上乘以倍率


                    item.DiscountReturn = CalcWhiteReturnPoint(0, item.DolarPerGrain, item.Rapnet, item.Weight, 1, 0);

                    //客户看到的价格
                    if (customer != null)
                    {
                        //按退点计算
                        if (customer.IsRebate == 1 || customer.IsRebate == null)
                        {
                            //计算客户价格--白钻   //原退点 +当前供应商的退点 +全局退点+客户退点 
                            item.CustomerDolarPerCarat = (decimal)(item.Rapnet * (decimal)((100 + Convert.ToDecimal(sourceDisc) + customer.Rebate) / 100)) * tempDouble;//客户美金每卡 2017-04-01
                            item.CustomerDolarPerGrain = item.CustomerDolarPerCarat * (decimal)item.Weight.Value;//客户美金总价 2017-01-19
                            item.CustomerRMBPerCarat = item.CustomerDolarPerCarat * GetRate(setting);
                            //RMB单粒价格
                            item.CustomerRMBPerGrain = item.CustomerRMBPerCarat * (decimal)item.Weight.Value; //只在粒上乘以倍率

                            //美元单粒价 		= RAPNET * (100 + 相应退点) / 100 * 重量
                            item.CustomerDiscountReturn = CalcWhiteReturnPoint(0, item.CustomerDolarPerGrain, item.Rapnet, item.Weight, 1, 0);
                        }
                        else if (customer.IsRebate == 0)
                        {
                            item.CustomerDolarPerCarat = (decimal)(item.Rapnet * (decimal)((100 + Convert.ToDecimal(sourceDisc)) / 100)) * tempDouble * customer.Rebate;
                            item.CustomerDolarPerGrain = item.CustomerDolarPerCarat * (decimal)item.Weight.Value;//客户美金总价 2017-01-19
                            item.CustomerRMBPerCarat = item.CustomerDolarPerCarat * GetRate(setting);
                            //RMB单粒价格
                            item.CustomerRMBPerGrain = item.CustomerRMBPerCarat * (decimal)item.Weight.Value; //只在粒上乘以倍率

                            //美元单粒价 		= RAPNET * (100 + 相应退点) / 100 * 重量
                            item.CustomerDiscountReturn = CalcWhiteReturnPoint(0, item.CustomerDolarPerGrain, item.Rapnet, item.Weight, 1, 0);

                        }
                    }  
                }
            }
            catch (Exception ee)
            {
                item.RMBPerGrain = 0;
                item.RMBPerCarat = 0;
                //item.CustomerDiscountReturn = 0;
                //item.CustomerRMBPerCarat = 0;
                //item.CustomerRMBPerGrain = 0;
                item.SourceDolarPerGrain = 0;
                Logger.Warn(typeof(DiamondsPriceHandler), "计算价格失败," + ee.Message);
            }
        }

        /// <summary>
        /// 计算价格 - 统包 Parcel 11-10
        /// </summary>
        public static void ComputeParcelPrice(ParcelInfoResult item, SystemSetting setting)
        {
            //if (item == null)
            //{
            //    return;
            //}

            //try
            //{
            //    //白统包
            //    if (item.Category == 1)
            //    {
            //        item.CustomerPrice = item.Price * setting.GetGlobalRate();//全局白统包倍率    公司美金每卡 = 原美金每卡 * 全局倍率 
            //        item.CustomerRMBPrice = item.Price * setting.GetGlobalRate() * setting.GetParcelSellRate();
            //    }
            //    else
            //    {
            //        //彩统包 Category = 2
            //        item.CustomerPrice = item.Price * setting.GetGlobalFancyRate();//全局彩统包倍率
            //        item.CustomerRMBPrice = item.Price * setting.GetGlobalFancyRate() * setting.GetParcelSellRate();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    item.CustomerPrice = 0;
            //    item.CustomerRMBPrice = 0;
            //    Logger.Warn(typeof(DiamondsPriceHandler), "计算价格失败," + ex.Message);
            //}

        }


        /// <summary>
        /// 计算给二级的RMB价格 - 统包 Parcel 11-12
        /// </summary>
        /// <param name="item"></param>
        /// <param name="setting"></param>
        public static void ComputeParcelPriceTwo(ParcelInfoResult item, SystemSetting setting)
        {
            //if (item == null)
            //{
            //    return;
            //}

            //try
            //{
            //    //白统包
            //    if (item.Category == 1)
            //    {
            //        item.CustomerPrice = item.Price * setting.GetGlobalRate() * setting.GetParcelSellRate();//全局白统包倍率    给二级的RMB每卡价格 = 一级原每卡美金 * 一级全局倍率 * 一级统包售出汇率 
            //    }
            //    else
            //    {
            //        //彩统包 Category = 2
            //        item.CustomerPrice = item.Price * setting.GetGlobalFancyRate() * setting.GetParcelSellRate();//全局彩统包倍率
            //    }
            //}
            //catch (Exception ex)
            //{
            //    item.CustomerPrice = 0;
            //    Logger.Warn(typeof(DiamondsPriceHandler), "计算价格失败," + ex.Message);
            //}

        }
        //分析4c折扣
        public static IList<Group_4C> GetGroupCCCC(int lib, string str)
        {
            if (str == null || str == "" || str.Trim().Length < 1) return null;
            else
            {
                if (System.Web.HttpContext.Current.Cache.Get("Cache:Group4C" + lib.ToString()) == null)
                {
                    str = str.TrimEnd(';');//去多组合的末尾;

                    string[] obj = str.Replace("\n", "").Replace("\r", "").Split(';');  //分组存相对应的折扣
                    IList<Group_4C> lv2CCCCs = new List<Group_4C>();

                    //1.形状
                    for (int i = 0; i < obj.Length; i++)
                    {
                        Group_4C lv2CCCC = new Group_4C();
                        //round 0.30-0.39 h si1 2;
                        string[] temps = obj[i].Replace("white#", "").Replace("fancy#", "").Split('#');
                        if (temps.Length > 1)
                        {
                            lv2CCCC.Shape = temps[0];
                            //2.重量
                            if (temps[1].Contains("-"))
                            {
                                var weights = temps[1].Split('-');
                                lv2CCCC.MinWeight = Convert.ToDecimal(weights[0]);
                                lv2CCCC.MaxWeight = Convert.ToDecimal(weights[1]);
                            }
                            else
                            {
                                lv2CCCC.MinWeight = 0.01M;
                                lv2CCCC.MaxWeight = 999.99M;
                            }

                            lv2CCCC.Double = temps[2] == "" ? 1 : Convert.ToDecimal(temps[2]);
                            lv2CCCC.Dis = temps[3] == "" ? 0 : Convert.ToDecimal(temps[3]);
                            lv2CCCCs.Add(lv2CCCC);
                        }
                    }
                    //第一次访问5分钟后过期，免得修改了4c或金额得改缓存设置
                    System.Web.HttpContext.Current.Cache.Insert("Cache:Group4C" + lib.ToString(), lv2CCCCs, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5));
                    return lv2CCCCs;
                }
                else
                {
                    return System.Web.HttpContext.Current.Cache.Get("Cache:Group4C" + lib.ToString()) as IList<Group_4C>;
                }

            }
        }

        /// <summary>
        /// 全局销售汇率 -裸钻
        /// </summary>
        /// <returns></returns>
        public static decimal GetRate(SysSettingInfo setting)
        {
            if (setting.Rate.HasValue && setting.Rate > 0)
            {
                return setting.Rate.Value;
            }
            return 1;
        }


        /// <summary>
        /// 全局采购汇率 - 裸钻
        /// </summary>
        /// <returns></returns>
        public static decimal GetPurchaseExchangeRate(SysSettingInfo setting)
        {
            if (setting.PurchaseExchangerate.HasValue && setting.PurchaseExchangerate > 0)
            {
                return setting.PurchaseExchangerate.Value;
            }
            return 1;
        }


        /// <summary>
        /// 全局白钻退点
        /// </summary>
        /// <returns></returns>
        public static decimal GetGlobalDiscountReturn(SysSettingInfo setting)
        {
            if (setting.GlobalDiscountReturn.HasValue)
            {
                return setting.GlobalDiscountReturn.Value;
            }
            return 0;
        }

        /// <summary>
        /// 全局彩钻退点
        /// </summary>
        /// <returns></returns>
        public static decimal GetGlobalFancyDiscountReturn(SysSettingInfo setting)
        {
            if (setting.GlobalFancyDiscountReturn.HasValue)
            {
                return setting.GlobalFancyDiscountReturn.Value;
            }
            return 0;
        }
        #region 计算退点
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ConfirmUSD">美元单粒价</param>
        /// <param name="Rapnet">Rapnet</param>
        /// <param name="Weight">Weight</param>
        /// <param name="Discounts">Discounts</param>
        /// <param name="SourceDolarPerGrain">原单粒价</param>
        /// <returns></returns>
        public static decimal? CalcWhiteReturnPoint(int IsFancy, decimal? ConfirmUSD, decimal? Rapnet, decimal? Weight, decimal? Discounts, decimal? SourceDolarPerGrain)
        {
            decimal? ReturnPoint = 0;
            if (IsFancy != 1)
            {
                //美元单粒价 		= RAPNET * (100 + 相应退点) / 100 * 重量
                ReturnPoint = ConfirmUSD * Discounts / Weight * 100 / Rapnet - 100;
            }
            else
            {
                //美元单粒价 		= 原单粒价 * (100 + 退点) / 100   
                ReturnPoint = ConfirmUSD * Discounts * 100 / SourceDolarPerGrain - 100;
            }
            return ReturnPoint;
        }
        #endregion
    }
}